<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\UserOrder;
use app\admin\model\User;
use app\admin\model\Admin;
use app\admin\model\AdminArticle;
use app\admin\model\ShopCategory;
use app\admin\model\ShopUserCategory;
use app\admin\model\ShopOrder;
use app\admin\model\UserCoupon;
use app\admin\model\Shop;
use app\admin\model\Product;
use app\admin\model\GroupChat;
use app\admin\model\GroupChatUser;
use app\admin\model\ProductMessage;
use app\admin\model\DistributeTask;
use app\admin\model\ChatMessage;
use app\admin\model\TaskScheduled;
use app\admin\model\OrderLog;
use app\admin\model\AreaWorldwide;
use think\Db;
use think\Exception;

class Dingshi extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {-
        parent::_initialize();
    }

    //排队订单超24小时
    public function dispose_order_paidui(){
        //存在则操作
		Db::startTrans();
		try {
            $where = [
                'paidui'=>1,
                'status'=>2
            ];
            $lists=UserOrder::where($where)->group('product_id')->select();
            foreach ($lists as $v) {
                $where['product_id'] = $v['product_id'];
                $order = UserOrder::where($where)->order('add_time desc')->find();
                //时间最近的那一个订单
                if((time() - $order['add_time']) > (24*3600) ){
                    
                    $info = UserOrder::where($where)->order('add_time asc')->find();
                    $list = UserOrder::where(['id'=>['neq',$info['id']],'paidui'=>1,'status'=>2,'product_id'=>$info['product_id']])->select();
                    if($list){
                        //存在则退款
                        foreach ($list as $v) {
                            $arr = ['user_id'=>$v['id'],'order_id'=>$v['id'],'ship_type'=>$v['ship_type'],'status'=>$v['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                            if($v['ship_type'] == 1){
                                //如果是买家付邮则需要退运费
                                $arr['text'] = '买家付邮退款';
                                if($v['pay_type'] == 'dy'){
                                    $pay = new Pay();
                                    $pay->dy_refund($v,$v['pay_fee'],User::where(['id'=>$v['user_id']])->value('nickname'),$arr);
                                }else{
                                    Pay::doOrderRefund($v,$v['pay_fee'],User::where(['id'=>$v['user_id']])->value('nickname'),$arr);
                                }
                            }
                            OrderLog::insert($arr);
                        }
                    }
                    UserOrder::where(['id'=>$info['id']])->update(['paidui'=>0]);
                }
            }
			Db::commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
    }

    public function update__group_chat_user1(){
        $redis = redis_init();
        $list = GroupChat::order('id asc')->select();
        foreach ($list as $v) {
            $name = 'group_chat_user_sum'.$v['identification'];
            $info = $redis->get($name);
            if($info){
                $redis->set($name,0);
                $infos = GroupChatUser::field('id')->where(['group_chat_id'=>$v['id']])->select();
                foreach ($infos as $vo) {
                    GroupChatUser::where(['id'=>$vo['id']])->setInc('unread_num',$info);
                }
                break;
            }
        }
    }

    public function update__group_chat_user2(){
        $redis = redis_init();
        $list = GroupChat::order('id desc')->select();
        foreach ($list as $v) {
            $name = 'group_chat_user_sum'.$v['identification'];
            $info = $redis->get($name);
            if($info){
                $redis->set($name,0);
                $infos = GroupChatUser::field('id')->where(['group_chat_id'=>$v['id']])->select();
                foreach ($infos as $vo) {
                    GroupChatUser::where(['id'=>$vo['id']])->setInc('unread_num',$info);
                }
                break;
            }
        }
    }



    //买家包邮-72小时未确认发货-则转回积分
    public function auto_back(){
        $time=time()-3600*24*2;
        $orders=UserOrder::where(array('status'=>2,'add_time'=>['<',$time]))->select();
        if($orders){
            foreach($orders as $order){
                $product=Product::where(array('id'=>$order['product_id']))->find();
                $user = User::where(['id'=>$product['user_id']])->find();
                ProductMessage::add(array('product_id'=>$order['product_id'],'message_id'=>0,'title'=>'卖家'.$user['nickname'].'未确认发货【'.$product['title'].'】，积分退回','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
               
                $arr = ['user_id'=>$order['user_id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                if($order['ship_type'] == 1){
                    //如果是买家付邮则需要退运费
                    $arr['text'] = '买家付邮退款';
                    if($order['pay_type'] == 'dy'){
                        $pay = new Pay();
                        $pay->dy_refund($order,$order['pay_fee'],$order['user_id'],$arr);
                    }else{
                        Pay::doOrderRefund($order,$order['pay_fee'],$order['user_id'],$arr);
                    }
                    order_cancel($order);
                }else{
                    $arr['text'] = '自提取消订单';
                    //退回积分
                    roseandlog($order['user_id'],$order['total_money'],18,'订单超时，退回交易额');
                    ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'卖家发货超时系统自动取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                    Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
                    UserOrder::where(array('id'=>$order['id']))->save(array('status'=>-1,'reason'=>'卖家发货超时','paidui'=>0,'paidui_content'=>''));
                }
            }
        }
        exit('order to back over');
    }

    //未支付订单自动取消
    public function no_payment(){
        $time=time()-900;
        //未支付订单
        $where = ['status'=>1,'add_time'=>['<',$time],'ship_type'=>1];
        $orders=UserOrder::where($where)->select();
 
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(['status'=>1]);
                Product::where(array('id'=>['in',$b['product_ids']]))->update(array('is_sale'=>0));
            }
        }

        $time=time()-300;
        //未支付订单
        $where = ['status'=>1,'add_time'=>['<',$time],'ship_type'=>1];
        $orders=ShopOrder::where($where)->select();
        if($orders){
            foreach($orders as $a=>$v){
                ShopOrder::where(array('id'=>$v['id']))->update(['status'=>1]);
                if($v['coupon_id']){
                    UserCoupon::where(['id'=>$v['coupon_id']])->update(['status'=>1]);
                }
                // 取消订单商品状态更新
                Product::where(['id'=>$v['product_id']])->update(array('is_sale'=>0));
            }
        }
        exit('order to complete over');
    }

    //已发货订单，48小时发送短息提醒   72小时候自动确认收货
    public function auto_recieve(){
        $time2=time()-3600*24*2;
        $time3=time()-3600*24*3;

        //自提  未点击已发货状态
        $where = ['ship_type'=>2,'status'=>2,'add_time' => ['between', [$time2, $time3]]];
        //买家付邮  未点击预约快递状态
        $where1 = ['ship_type'=>1,'status'=>2,'add_time' => ['between', [$time2, $time3]]];
        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){   
            $query->where($where1);
        })->select();
        $arrIds = [];
        if($orders){
            foreach($orders as $a=>$b){
                $arrIds[] = $b['id'];
                //取消订单并发送站内消息和短信提醒
                $arr = [
                    'content' => '您有笔订单待处理,请及时查看。',
                    'user_id' => 439,
                    'add_time'=>time(),
                ];
                if($b['ship_type'] == 1){  //付邮发给卖家
                    $arr['js_user_id'] = $b['shop_id'];
                }else{  //自提发给买家
                    $arr['js_user_id'] = $b['user_id'];
                }
                $arr['sort'] = $arr['js_user_id'].'00'.$arr['user_id'];
                ChatMessage::insert($arr);
            }
        }
       
        //自提  已发货状态
        $where = ['ship_type'=>2,'status'=>['in','2,3'],'is_shopping'=>0,'add_time' => ['<', $time3]];
        //买家付邮  预约快递或已发货状态
        $where1 = ['ship_type'=>1,'status'=>['in','2,3,6'],'is_shopping'=>0,'add_time' => ['<', $time3]];
        if($arrIds){
            $where['id']=['not in',$arrIds];
            $where1['id']=['not in',$arrIds];
        }
        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->select();
        if($orders){
            foreach($orders as $a=>$b){
                $user= User::where(['id'=>$b['user_id']])->find();
                $arr = ['user_id'=>$user['id'],'order_id'=>$b['id'],'ship_type'=>$b['ship_type'],'status'=>$b['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                Db::startTrans();
                try {
                    if($b['status'] == 2 || $b['status'] == 6){ //取消订单.
                      
                        if($b['ship_type'] == 1){
                            //如果是买家付邮则需要退运费
                            //待支付的不需要退
                            if($b['status'] == 2){
                                $arr['text'] = '买家付邮退款';
                                if($b['pay_type'] == 'dy'){
                                    $pay = new Pay();
                                    $pay->dy_refund($b,$b['pay_fee'],$user['nickname'],$arr);
                                }else{
                                    Pay::doOrderRefund($b,$b['pay_fee'],$user['nickname'],$arr);
                                }
                                order_cancel($b);
                            }else{
                                $arr['text'] = '待支付订单取消';
                            }
                        }else{
                            $arr['text'] = '自提取消订单';
                            //退回积分
                            roseandlog($b['user_id'],$b['total_money'],18,'取消订单，退回');
                            $product=Product::where(array('id'=>$b['product_id']))->find();
                            ProductMessage::insert(array('product_id'=>$b['product_id'],'title'=>'买家'.$user['nickname'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                            UserOrder::where(array('id'=>$b['id']))->update(array('status'=>-1,'paidui'=>0,'paidui_content'=>''));
                        }
                        Product::where(array('id'=>$b['product_id']))->update(array('is_sale'=>0,'status'=>-1));

                        
                    }elseif($b['status'] == 3 && $b['is_shopping'] == 0){
                        $arr['text'] = '完成订单';
                        UserOrder::where(array('id'=>$b['id']))->update(array('status'=>5,'recieve_time'=>time()));
                        $product=Product::where(array('id'=>$b['product_id']))->find();
                        if($product){
                            //首次订单完成给奖励
                            $redis = redis_init();
                            $name = 'add_score_25_'.$product['user_id'];
                            $info = $redis->get($name);
                            if(!$info){
                                //未获取过奖励则直接给奖励
                                roseandlog($product['user_id'],3,25,'首次订单完成');
                                $redis->set($name,time());
                            }
                            roseandlog($product['user_id'],$b['total_money'],6,'售出商品获得');
                            ProductMessage::insert(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                OrderLog::insert($arr);
            }
        }


        $time=time()-3600*24*10;
        //商城订单10天后自动收货
        $where = ['ship_type'=>1,'status'=>3,'is_shopping'=>1,'add_time' => ['<', $time]];
        $orders=UserOrder::where($where)->select();
        if($orders){
            foreach($orders as $a=>$b){
                $arr = ['user_id'=>$b['user_id'],'order_id'=>$b['id'],'ship_type'=>$b['ship_type'],'status'=>$b['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                Db::startTrans();
                try {
                    $arr['text'] = '完成订单';
                    UserOrder::where(array('id'=>$b['id']))->update(array('status'=>5,'recieve_time'=>time()));
                    $product=Product::where(array('id'=>$b['product_id']))->find();
                    if($product){
                        //首次订单完成给奖励
                        $redis = redis_init();
                        $name = 'add_score_25_'.$product['user_id'];
                        $info = $redis->get($name);
                        if(!$info){
                            //未获取过奖励则直接给奖励
                            roseandlog($product['user_id'],3,25,'首次订单完成');
                            $redis->set($name,time());
                        }
                        order_edit_price($product['user_id'],$b['price']);
                        ProductMessage::insert(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                OrderLog::insert($arr);
            }
        }
    }

    //实时监控抽奖是否到开奖时间
    /* public function start_prize(){
        $where = [
            'status'=>0,
            'prize_time'=>['<=',time()]
        ];
        $list = Prize::where($where)->select();
        if($list){
            foreach ($list as &$v) {
                $where = [
                    'status'=>0,
                    'prize_id'=>$v['id']
                ];
                if($v['one_award_user_list']){
                    $one_award_user_list = explode(',',$v['one_award_user_list']);
                    $where['id'] = ['in',$one_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>1]);
                    //中奖得积分
                    if($v['one_prize']){
                        foreach ($one_award_user_list as $one) {
                            roseandlog(PrizeUser::where('id',$one)->value('user_id'),$v['one_prize'],31,'中奖得积分');
                        }
                    }
                }
                if($v['tow_award_user_list']){
                    $tow_award_user_list = explode(',',$v['tow_award_user_list']);
                    $where['id'] = ['in',$tow_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>2]);
                    //中奖得积分
                    if($v['tow_prize']){
                        foreach ($tow_award_user_list as $tow) {
                            roseandlog(PrizeUser::where('id',$tow)->value('user_id'),$v['tow_prize'],31,'中奖得积分');
                        }
                    }
                }
                if($v['three_award_user_list']){
                    $three_award_user_list = explode(',',$v['three_award_user_list']);
                    $where['id'] = ['in',$three_award_user_list];
                    PrizeUser::where($where)->update(['status'=>1,'prize_grade'=>3]);
                    //中奖得积分
                    if($v['three_prize']){
                        foreach ($three_award_user_list as $three) {
                            roseandlog(PrizeUser::where('id',$three)->value('user_id'),$v['three_prize'],31,'中奖得积分');
                        }
                    }
                }
                unset($where['id']);
                PrizeUser::where($where)->update(['status'=>-1]);
                Prize::where(['id'=>$v['id']])->update(['status'=>1]);
            }
        }
    } */


    
    //图片压缩
    public function ysImg(){

        $info = Product::where('id',5)->find();

        $src = date('Ymd') . '/' .time().rand(1000, 9999).'.png';
        $image = \think\Image::open($info['video_img']);
        // 按照原图的比例生成一个最大为600*600的缩略图替换原图
        $image->thumb(1300, 1300)->save(ROOT_PATH . 'public' . DS . 'uploads/'.$src);

        dd($src);
    }



    //推送离线消息
    public function sendLxMessage(){
        
    }



    //处理文件数据录入数据库
    public function area_worldwide(){
        $file = file_get_contents('worldAddress.txt');
        $rep = str_replace("\r\n", ',', $file);
        $cont = explode(',', $rep);
        $one = 0;  //对应的一级ID
        $one_name = '';  //对应的一级ID
        $tow = 0;  //对应的二级ID
        $tow_name = '';  //对应的二级ID
        for ($i = 0;$i < count($cont);$i++) {
            //判断有多少空格
            $spaceCount  = 0;
            for ($j = 0;$j < 6;$j++) {
                if($cont[$i][$j] != ' '){
                    break;
                }elseif ($cont[$i][$j] == ' ') {
                    $spaceCount += 1;
                }
            }
            $items =  explode('#', trim($cont[$i]));
            if($spaceCount == 0){
                $data = [
                    'pid' => 0,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$items[0],
                    'level'=>0,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    $one = $info['id'];
                    $one_name = $items[0];
                    continue;
                }
                $one = AreaWorldwide::insertGetId($data);    
                $one_name = $items[0];
            }elseif($spaceCount == 2){
                $data = [
                    'pid' => $one,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$one_name.','.$items[0],
                    'level'=>1,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    $tow = $info['id'];
                    $tow_name = $items[0];
                    continue;
                }
                $tow = AreaWorldwide::insertGetId($data); 
                $tow_name = $items[0];
            }elseif($spaceCount == 4){
                $data = [
                    'pid' => $tow,
                    'shortname'=>$items[0],
                    'name'=>$items[1],
                    'mergename'=>$one_name.','.$tow_name.','.$items[0],
                    'level'=>2,
                ];
                $info = AreaWorldwide::where($data)->find();
                if($info){
                    continue;
                }
                AreaWorldwide::insertGetId($data); 
            }
        }
    }

    
    //查询接单任务超过过期时间还未回传用户
    public function getDistributeTask(){
        $where = [
            'status'=>1,
            'receive_time'=>['<',time()-3600],
            'user_content'=>'',
            'task_type'=>['<',5]
        ];
        $ids = DistributeTask::where($where)->column('id');

        Db::startTrans();
            try {
                if($ids){
                    DistributeTask::where(['id'=>['in',$ids]])->update(['status'=>-2]);
                    //通过审核后管理商户余额
                    set_shop_task_price($ids,1);
                }
                var_dump($ids);
                $where = [
                    'status'=>1,
                    'receive_time'=>['<',time()-(3600*36)],
                ];
                $ids = DistributeTask::where($where)->column('id');
            
                if($ids){
                    DistributeTask::where(['id'=>['in',$ids]])->update(['status'=>-2]);
                    //通过审核后管理商户余额
                    set_shop_task_price($ids,1);
                }
                var_dump($ids);
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

       
    }

    //检查帖子是否被删除
    public function examine_invitation(){
        $where = [
            'examine_time'=>['<',time()-(3600*24)],
            'receive_time'=>['>',time()-(3600*24*30)],
            'is_del_old'=>0,
            'status'=>3,
            'id'=>['>',10000]
        ];
        $list = DistributeTask::where($where)->limit(0,100)->select();
        foreach ($list as $v) {
            DistributeTask::where(['id'=>$v['id']])->update(['examine_time'=>time()]);
            //查看该用户是否删除了帖子
            $title = $v['user_content'];
            if(!$title){
                continue;
            }
            $datas= [];
            if(strpos($title, 'http://') !== false){
                $res = explode('http://',$title);
                if(empty($res[1])){
                    continue;
                }
                $res = explode('，',$res[1]);
                $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
                foreach ($headers as $vs) {
                    if (strpos($vs, 'Location') !== false) {
                        $res = explode('?',$vs);
                        if(empty($res[0])){
                            continue;
                        }
                        $datas = explode('/',$res[0]);
                    }
                }
            }
            if(count($datas) == 2 && $datas[1] == '404' && $v['is_del_old'] == 0){
                DistributeTask::where(['id'=>$v['id']])->update(['is_del_old'=>1]);
            }
        }
    }


    // $list = $this->model->where(['status'=>['neq',2],'appuid'=>''])->select();
    //     foreach ($list as $v) {
    //         $title = $v['user_content'];
    //         if(!$title){
    //             continue;
    //         }
    //         if (strpos($title, 'https://') !== false) {
    //             $res = explode('?',$title);
    //             if(empty($res[0])){
    //                 continue;
    //             }
    //             $datas = explode('/',$res[0]);
    //         }elseif(strpos($title, 'http://') !== false){
    //             $res = explode('http://',$title);
    //             if(empty($res[1])){
    //                 continue;
    //             }
    //             $res = explode('，',$res[1]);
    //             $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
    //             foreach ($headers as $vs) {
    //                 if (strpos($vs, 'Location') !== false) {
    //                     $res = explode('?',$vs);
    //                     if(empty($res[0])){
    //                         continue;
    //                     }
    //                     $datas = explode('/',$res[0]);
    //                 }
    //             }
    //         }
    //         if(count($datas) > 2){
    //             $this->model->where(['id'=>$v['id']])->update(['appuid'=>$datas[count($datas)-1]]);
    //         }
    //     }



    //任务自动上架计划任务
    public function putaway_task_scheduled()
    {
        $list = TaskScheduled::where(['status'=>1])->select();
        $redis = redis_init();
        $is_send = false;
        foreach ($list as $v) {
            if($v['time'] && $v['num']){
                $v['time'] = strtotime(date('Y-m-d '.$v['time'].':00:00',time()));
                if(!$redis->get($v['time'].$v['id']) && $v['time'] < time()){
                    //当前时间大于定时时间 且没有发过
                    $where = ['type'=>$v['type'],'status'=>-3];
                    if($v['category_id']){
                        $where['category_id'] = $v['category_id'];
                    }
                    $task_list = DistributeTask::field('id')->where($where)->select();
                    if($task_list){
                        $ids = [];
                        for ($i=0; $i < $v['num']; $i++) { 
                            //每次随机一个
                            $index = rand(0,count($task_list)-1);
                            $ids[] = $task_list[$index]['id'];
                            unset($task_list[$index]);
                            //重新排序
                            sort($task_list);
    
                            if(count($task_list) == 0){
                                break;
                            }
                        }
    
                        if($ids){
                            $is_send = true;
                            DistributeTask::where(['id'=>['in',$ids]])->update(['status'=>0]);
                            var_dump($ids);
                        }
                        $redis->set($v['time'].$v['id'],1);
                    }
                }
            }
        }

        if($is_send){
            $redis = redis_init();
            $name = 'send_subscription_news';
            $redis->set($name,1);
            //send_task_subscription();
            // $ids = User::where(['is_task_subscription'=>1])->column('id');
            // if($ids){
            //     $idss = DistributeTask::where(['status'=>1,'user_id'=>['in',$ids]])->whereTime('receive_time', 'today')->column('user_id');
            //     $arr_ids = [];
            //     foreach ($ids as $v) {
            //         if(!in_array($v,$idss)){
            //             $arr_ids[] = $v;
            //         }
            //     }
            //     if($arr_ids){
            //         foreach ($arr_ids as $vs) {
            //             //查看用户今天是否已经接单
            //             $data = [
            //                 "thing1"=>["value"=>'余享新任务已更新'],
            //                 "time3"=>["value"=>date('Y-m-d H:i:s',time())]
            //             ];
            //             send_subscription($vs,'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
            //         }
            //     }
            // }
        }
        

    }


    //周六上传任务超过2小时自动上架
    public function shop_auto_send()
    {
        $today = date('D'); // 获取当前星期几（英文）
        if ($today == 'Sat' || $today == 'Sun') {
            $time =  strtotime(date('Y-m-d',time()));
            $where = [
                'status'=>-3,
                'shop_id'=>['>',0],
                'add_time'=>['>',$time]
            ];
            $list = DistributeTask::where($where)->select();
            if($list){
                foreach ($list as $v) {
                    if((time()-$v['add_time']) > 7200){
                        //自动上架
                        DistributeTask::where(['id'=>$v['id']])->update(['status'=>0]);
                    }
                }
            }
        }
    }


    //发送订阅消息
    public function send_subscription_news()
    {
        $redis = redis_init();
        $name = 'send_subscription_news';
        $info = $redis->get($name);
        if($info){
            send_task_subscription();
            $redis->set($name,'');
            var_dump('操作成功');
        }else{
        }
    }



    //用户标签动态变更
    public function user_label_update()
    {
        $redis = redis_init();
        $day = date('Y-m-d',time()).'ShopCategory';
        set_time_limit(0);
        $list = ShopCategory::select();
        foreach ($list as $v) {
            $redis_str = $day.$v['id'];
            if($redis->get($redis_str)){
                continue;
            }
            $shop_names = Shop::where(['category_id'=>$v['id']])->column('name');
            $task = DistributeTask::field('sum(statistics_num) as statistics_sum,count(id) as count')->where(['status'=>3,'type'=>['in',$shop_names]])->find();
            $count = 0;
            if($task['count'] > 0){
                $count = floor($task['statistics_sum']/$task['count']);
            }else{
                continue;
            }
            $userList = User::field('id')->where(['task_price'=>['>',0]])->select();
            foreach ($userList as $vs) {
                $redis_user_str = $day.$v['id'].$vs['id'];
                if($redis->get($redis_user_str)){
                    continue;
                }
                $userTask = DistributeTask::field('sum(statistics_num) as statistics_sum,count(id) as count')->where(['user_id'=>$vs['id'],'status'=>3,'type'=>['in',$shop_names]])->find();
                $user_count = 0;
                if($userTask['count'] > 0){
                    $user_count = floor($userTask['statistics_sum']/$userTask['count']);
                }else{
                    continue;
                }
                if($user_count > $count){
                    $ShopUserCategory = ShopUserCategory::where(['user_id'=>$vs['id'],'category_id'=>$v['id']])->find();
                    if(!$ShopUserCategory){
                        ShopUserCategory::insert(['user_id'=>$vs['id'],'category_id'=>$v['id']]);
                    }
                }else{
                    ShopUserCategory::where(['user_id'=>$vs['id'],'category_id'=>$v['id']])->delete();
                }
                $redis->set($redis_user_str,1);
            }

            $redis->set($redis_str,1);
        }
    }


    //后台工作任务
    public function plan_admin_article()
    {   
        $list = AdminArticle::where(['type'=>1])->select();
        if($list){
            $date = time();
            $date = date("l", $date);
            $date = strtolower($date);
            if($date =="saturday" || $date =="sunday") {
                return;
            }
            foreach ($list as &$v) {
                if(!$v['plan_complete_time']){
                    continue;
                }
              
                


                if($v['repetition'] == 1 ){
                    $time = strtotime(date('Y-m-d'));  //获取当天时间戳
                    //每日重复
                    $where = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'pid'=>$v['id']
                    ];
                    $where1 = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'id'=>$v['id']
                    ];
                    //查询是否存在今天的数据  如果存在则不更新
                    $info = AdminArticle::where($where)->whereOr(function($query) use ($where1){
                        $query->where($where1);
                    })->find();
                 
                    if(!$info){
                        $plan_complete_time = AdminArticle::where(['pid'=>$v['id']])->order('id desc')->value('plan_complete_time');
                        if(!$plan_complete_time){
                            $plan_complete_time = $v['plan_complete_time']; 
                        }
                        $time = date('H:i:s',$plan_complete_time);
                        $time = strtotime(date('Y-m-d ',time()).$time);//strtotime();
                        $arr = [];
                        $arr['add_time'] = time();
                        $arr['plan_complete_time'] = $time;
                        $arr['type'] = 2;
                        $arr['admin_id'] = $v['admin_id'];
                        $arr['remark'] = $v['remark'];
                        $arr['title'] = $v['title'];
                        $arr['pid'] = $v['id'];
                        $arr['repetition'] = $v['repetition'];
                        $arr['audit_admin_id'] = $v['audit_admin_id'];
                       
                        $info = AdminArticle::insert($arr);
           
                    }
                }elseif($v['repetition'] == 2){
                    //每周重复
                    $time = strtotime('Monday this week');  //获取当天时间戳
                    //每周重复
                    $where = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'pid'=>$v['id']
                    ];
                    $where1 = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'id'=>$v['id']
                    ];
                    //查询是否存在今天的数据  如果存在则不更新
                    $info = AdminArticle::where($where)->whereOr(function($query) use ($where1){
                        $query->where($where1);
                    })->find();
                    if(!$info){
                        $plan_complete_time = AdminArticle::where(['pid'=>$v['id']])->order('id desc')->value('plan_complete_time');
                        if(!$plan_complete_time){
                            $plan_complete_time = $v['plan_complete_time']; 
                        }
                        $arr = [];
                        $arr['add_time'] = time();
                        $arr['plan_complete_time'] = $plan_complete_time + 3600*24*7;
                        $arr['type'] = 2;
                        $arr['admin_id'] = $v['admin_id'];
                        $arr['remark'] = $v['remark'];
                        $arr['title'] = $v['title'];
                        $arr['pid'] = $v['id'];
                        $arr['repetition'] = $v['repetition'];
                        $arr['audit_admin_id'] = $v['audit_admin_id'];
                        $info = AdminArticle::insert($arr);
                    }
                }elseif($v['repetition'] == 3){
                    //每月重复
                    $time = strtotime(date('Y-m-01', strtotime(date('Y-m-d'))));  //获取当天时间戳
                    //每月重复
                    $where = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'pid'=>$v['id']
                    ];
                    $where1 = [
                        'plan_complete_time'=>['>',$time],
                        'admin_id'=>$v['admin_id'],
                        'id'=>$v['id']
                    ];
                    //查询是否存在今天的数据  如果存在则不更新
                    $info = AdminArticle::where($where)->whereOr(function($query) use ($where1){
                        $query->where($where1);
                    })->find();
                    if(!$info){
                        $plan_complete_time = AdminArticle::where(['pid'=>$v['id']])->order('id desc')->value('plan_complete_time');
                        if(!$plan_complete_time){
                            $plan_complete_time = $v['plan_complete_time']; 
                        }
                        $arr = [];
                        $arr['add_time'] = time();
                        $arr['plan_complete_time'] = strtotime("+1 months",$plan_complete_time);
                        $arr['type'] = 2;
                        $arr['admin_id'] = $v['admin_id'];
                        $arr['remark'] = $v['remark'];
                        $arr['title'] = $v['title'];
                        $arr['pid'] = $v['id'];
                        $arr['repetition'] = $v['repetition'];
                        $arr['audit_admin_id'] = $v['audit_admin_id'];
                        $info = AdminArticle::insert($arr);
                    }
                }

            }
        }

    }

    //后台工作任务提醒
    public function tx_admin_article()
    {
        $list = AdminArticle::where(['is_remind'=>0,'status'=>0])->select();
        if($list){
            foreach ($list as &$v) {
                $mobile = Admin::where(['id'=>$v['admin_id']])->value('mobile');
                if($v['repetition'] == 1 || $v['repetition'] == 0){ //每天提醒  提前一个小时提醒
                    //提前一个小时提醒

                    if($v['plan_complete_time'] < time() + 3600){
                        AdminArticle::where(['id'=>$v['id']])->update(['is_remind'=>1]);
                        $this->dingding_push('你有每日任务待完成！别忘记了',$mobile);
                    }
                }elseif($v['repetition'] == 2){
                    //提前一天小时提醒
                    if($v['plan_complete_time'] < time() + 3600*24){
                        AdminArticle::where(['id'=>$v['id']])->update(['is_remind'=>1]);
                        $this->dingding_push('你有每周任务待完成！别忘记了',$mobile);
                    }
                }elseif($v['repetition'] == 3){
                    //提前一天小时提醒
                    if($v['plan_complete_time'] < time() + 3600*24){
                        AdminArticle::where(['id'=>$v['id']])->update(['is_remind'=>1]);
                        $this->dingding_push('你有每月任务待完成！别忘记了',$mobile);
                    }
                }
            }
        }
    }



    //钉钉提醒
    public function dingding_push($content,$phone = '')
    {
        // 钉钉机器人Webhook URL
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=a4f91fb458c89603d0188c7b38c533ae0d807be1173113513a2c24843045b7c4";
        // 要@的人的手机号
        $atMobiles = array($phone);
        // 构造消息体
        $data = array (
            "msgtype" => "text",
            "text" => array (
                "content" => $content.' bot'
            ),
            "at" => array (
                "atMobiles" => $atMobiles,
                "isAtAll" => false
            )
        );
        // JSON编码消息体
        $data_string = json_encode($data);

        // 使用cURL发送POST请求
        $ch = curl_init($webhook);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
        );

        // 执行POST请求，获得结果
        $result = curl_exec($ch);
        curl_close($ch);
    }


    //系统查询超过一个月时间的商品是否还在功能
    public function product_is_in(){
        $where = [
            'status'=>1,
            'is_sale'=>0,
            'day'=> ['<',(time()-(30*24*3600))],
            'is_in'=>0
        ];
        $list = Product::where($where)->select();
        if($list){
            $arr = [];
            foreach ($list as $v) {
                if(!in_array($v['user_id'], $arr)){
                    $mobile = User::where(['id'=>$v['user_id']])->value('mobile');
                    //没有通知过则进行短信通知
                    send_mobile($mobile,'SMS_472080194');
                    Product::where($where)->where(['user_id'=>$v['user_id']])->update(['is_in'=>1]);
                    $arr[] = $v['user_id'];
                }
            }
        }else{
            echo '无数据';
        }

    }






    //查询快递信息详情
    public function getKuaiDetail(){

        $order = UserOrder::where(['freight'=>null,'kuaidinum'=>['neq','']])->select();

        foreach ($order as $v) {
            $param = [
                'taskId' => $v['taskId']
            ];
            $param = json_encode($param, JSON_UNESCAPED_UNICODE);
            $t = time() * 1000;
            $post_data = [

                'key'=>'wlSuxIGP3476',
                'sign'=>strtoupper(MD5($param.$t.'wlSuxIGP3476'.'155d139726d040e88207b0cc03481efa')),
                't'=>$t,
                'param'=>$param
            ];
            $url = 'https://poll.kuaidi100.com/order/borderapi.do?method=detail';
            // 发送post请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $result = curl_exec($ch);
            $data = json_decode($result, true);
            
            if($data['result'] && $data['returnCode'] == 200){
                $data = $data['data'];
                UserOrder::where(['id'=>$v['id']])->update(['freight'=>$data['freight'],'lastWeight'=>$data['lastWeight']]);
            }
        }

    }



    //没过5-20分钟自动增长浏览值
    public function want_count_z1(){
        $day = date('H',time());
        //20分钟一次
        if($day < 8 || $day >= 20){
            $where = [
                'status'=>1,
                'is_sale'=>0,
                'is_del'=>0
            ];
            $list = Product::field('id,want_count')->where($where)->order('id desc')->select();
            foreach ($list as $v) {
                Product::where(['id'=>$v['id']])->update(['want_count'=>$v['want_count']+1]);
            }
            echo '成功';
        }else{
            echo '';
        }

    }

    //没过5-20分钟自动增长浏览值
    public function want_count_z2(){
        $day = date('H',time());
        //5分钟一次
        if($day >= 8 || $day < 20){
            $where = [
                'status'=>1,
                'is_sale'=>0,
                'is_del'=>0
            ];
            $list = Product::field('id,want_count')->where($where)->order('id desc')->select();
            foreach ($list as $v) {
                Product::where(['id'=>$v['id']])->update(['want_count'=>$v['want_count']+1]);
            }
            echo '成功';
        }else{
            echo '';
        }
    }

}